package com.asy.ui.base;

import java.util.List;

import android.R.integer;
import android.app.Activity;
import android.graphics.Bitmap;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ImageView;

import com.asy.ui.base.AsyncImageLoader.ImageCallback;
import com.xinzhang.R;

public class ImageAndTextGridAdapter extends ArrayAdapter<ImageAndText> {  
	  
    private GridView gridView;  
    private AsyncImageLoader asyncImageLoader;  
    
    public ImageAndTextGridAdapter(Activity activity, List<ImageAndText> imageAndTexts, GridView gridView) {  
        super(activity, 0, imageAndTexts);  
        this.gridView = gridView;  
        asyncImageLoader = new AsyncImageLoader();  
        
    }  

    @Override
    public ImageAndText getItem(int position) {
    	// TODO Auto-generated method stub
    	return super.getItem(position);
    }
    
    public View getView(int position, View convertView, ViewGroup parent) {  
        Activity activity = (Activity) getContext();  
        Display display = activity.getWindowManager().getDefaultDisplay();
        double s=(double)display.getWidth()/(double)320;
        int imagewidth=(int)((double)76*s);
        
        View rowView = convertView;  
        ViewCache viewCache;  
        if (rowView == null) {  
            LayoutInflater inflater = activity.getLayoutInflater();  
            rowView = inflater.inflate(R.layout.itemtemp, null);  
            viewCache = new ViewCache(rowView);  
            viewCache.setWidth(imagewidth);
            rowView.setTag(viewCache);  
        } else {  
            viewCache = (ViewCache) rowView.getTag();  
            viewCache.setWidth(imagewidth);
        }  
        ImageAndText imageAndText = getItem(position);  

        
        String imageUrl = imageAndText.getImageUrl();  
        ImageView imageView = viewCache.getImageView();  
        imageView.setTag(imageUrl);  
        Bitmap cachedImage = asyncImageLoader.loadDrawable(imageUrl, new ImageCallback() {  
            public void imageLoaded(Bitmap bitmap, String imageUrl) {  
                ImageView imageViewByTag = (ImageView)gridView.findViewWithTag(imageUrl);  
                if (imageViewByTag != null) {  
                    imageViewByTag.setImageBitmap(bitmap);  
                }  
            }  
        });  
        if (cachedImage == null) {  
            imageView.setImageResource(R.drawable.r);  
        }else{  
            imageView.setImageBitmap(cachedImage);  
        }  

        return rowView;  
    }  

}  
